package com.itic.mall.system.users.usersmall.service;

import com.itic.appbase.applications.sys.syssetting.persistence.dao.SysSettingDao;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.constants.IticConst;
import com.itic.appbase.framework.common.constants.ResponseCode;
import com.itic.appbase.framework.common.service.CrudService;
import com.itic.appbase.framework.exception.definition.ParameterErrorException;
import com.itic.appbase.framework.type.*;
import com.itic.appbase.framework.utils.*;
import com.itic.mall.mobile.users.livingRate.entity.LivingRateResultVo;
import com.itic.mall.mobile.users.store.temp.Condition;
import com.itic.mall.system.goods.goodssku.service.GoodsSkuService;
import com.itic.mall.system.inter.finance.makeMoney.service.FinanceUserMakeMoneyService;
import com.itic.mall.system.inter.finance.makeMoneyLog.service.FinanceUserMakeMoneyLogService;
import com.itic.mall.system.inter.goods.goodssku.persistence.model.GoodsSku;
import com.itic.mall.system.inter.orders.detail.persistence.dao.OrdersDetailDao;
import com.itic.mall.system.inter.orders.detail.persistence.model.OrdersDetail;
import com.itic.mall.system.inter.orders.detail.persistence.model.OrdersDetailExample;
import com.itic.mall.system.inter.orders.item.persistence.model.OrdersItem;
import com.itic.mall.system.inter.users.openstore.persistence.dao.OpenStoreDao;
import com.itic.mall.system.inter.users.openstore.persistence.model.OpenStore;
import com.itic.mall.system.inter.users.pointslog.persistence.model.UsersPointslog;
import com.itic.mall.system.inter.users.userHelp.persistence.model.UsersHelp;
import com.itic.mall.system.inter.users.usersmall.persistence.dao.UsersMallDao;
import com.itic.mall.system.inter.users.usersmall.persistence.model.UsersMall;
import com.itic.mall.system.inter.users.usersmall.persistence.model.UsersMallExample;
import com.itic.mall.system.inter.users.usersmall.persistence.model.UsersMallExample.Criteria;
import com.itic.mall.system.inter.users.usersystem.controller.UserLevelVo;
import com.itic.mall.system.msg.phonesend.service.PhoneSendService;
import com.itic.mall.system.orders.item.service.OrdersItemService;
import com.itic.mall.system.pay.userlog.service.PayUserlogService;
import com.itic.mall.system.project.livingRate.service.LivingRateService;
import com.itic.mall.system.service.StoreInfoService;
import com.itic.mall.system.store.storeInfo.persistence.model.StoreInfo;
import com.itic.mall.system.users.pointslog.service.UsersPointslogService;
import com.itic.mall.system.users.userHelp.service.UsersHelpService;
import com.itic.mall.system.users.usercoupon.service.UsersCouponService;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service
@Transactional
public class UsersMallService
     extends CrudService<UsersMallDao,UsersMall,UsersMallExample> {
    @Autowired
    private UsersMallDao usersMallDao;
    @Autowired
    private OrdersDetailDao ordersDetailDao;
    @Autowired
    private OpenStoreDao openStoreDao;
    @Autowired
    private SysSettingDao sysSettingDao;
    @Autowired
    private StoreInfoService storeInfoService;
    @Autowired
    private PhoneSendService phoneSendService;
    @Autowired
    private UsersPointslogService usersPointslogService;
    @Autowired
    private UsersCouponService usersCouponService;
    @Autowired
    private LivingRateService livingRateService;
    @Autowired
    private PayUserlogService payUserlogService;
    @Autowired
    private FinanceUserMakeMoneyService financeUserMakeMoneyService;

    @Autowired
    private FinanceUserMakeMoneyLogService financeUserMakeMoneyLogService;
    @Autowired
    private OrdersItemService ordersItemService;
    @Autowired
    private GoodsSkuService goodsSkuService;
    @Autowired
    private UsersHelpService usersHelpService;
    
    private static String[] ignoreProperties = new String[] { };
    
    public UsersMall getUsersMallByname(String userNickName){
    	UsersMall temp = null;
    	if(StringHelper.isNotBlank(userNickName)){
    		UsersMallExample example = new UsersMallExample();
    		Criteria criteria = example.createCriteria();
    		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
    		criteria.andUserNickNameEqualTo(userNickName);
    		List<UsersMall> list = this.usersMallDao.selectByExample(example);
    		if(list.size()>0){
    			temp = list.get(0);
    		}
    	}
    	return temp;
    }
    public boolean updateUserMall(String newid,String id,String userNickName,String unionId,String userPhone,String userHeadImg,String invitingCode,Double moneyDB,Double preProfitDB,Double totalProfitDB,String openid,String invitingId,int successPeopleInt,String type) {
		return usersMallDao.updateUserMall(newid,id,userNickName,unionId,userPhone,userHeadImg,invitingCode,moneyDB,preProfitDB,totalProfitDB,openid,invitingId,successPeopleInt,type);
	}
    
	public UsersMall getByPhone(String phone) {
		return usersMallDao.getByPhone(phone);
	}

	public UsersMall getByUnionid(String unionid) {
		return usersMallDao.getByUnionid(unionid);
	}
	
	public UsersMall getByOpenid(String openid) {
		return usersMallDao.getByOpenid(openid);
	}
	
	public UsersMall addUbi(  UsersMall usersMall ){
		Integer jifeng = usersMall.getJifeng();
		//添加一条积分记录
		if( null != jifeng && jifeng>0 ){
			UsersPointslog usersPointslog = new UsersPointslog();
			usersPointslog.setPoints(jifeng);
			usersPointslog.setUserId(usersMall.getId());
			//usersPointslog.setPointsAmount(pointsAmount);
			usersPointslog.setType("001");
			usersPointslog.setChangeReason("新用户邀请获得10U币");
			usersPointslogService.add(usersPointslog);
		}
		return usersMall;
	}
	/**
	 * 获取用户信息
	 * @param userId
	 * @return
	 */
	public List<UserLevelVo> getUsersMallList(String userId,String levelDesc) {
		List<UserLevelVo> volist = new ArrayList<UserLevelVo>();
		if (StringHelper.isNotBlank(userId)) {
			UsersMallExample example = new UsersMallExample();
			Criteria criteria = example.createCriteria();
			criteria.andIdEqualTo(userId);
			criteria.andIsEffectiveEqualTo(DBConst.TRUE);
			List<UsersMall> list = this.usersMallDao.selectByExample(example);
			if(list.size()>0){
				UserLevelVo userLevelVo = new UserLevelVo();
				userLevelVo.setId(list.get(0).getId());
				userLevelVo.setLevelDesc(levelDesc);
				userLevelVo.setUserNickName(list.get(0).getUserNickName());
				userLevelVo.setLaiyuan(list.get(0).getIsActive());
				userLevelVo.setTotalComsum(list.get(0).getTotalComsum());
				userLevelVo.setUserPhone(list.get(0).getUserPhone());
				userLevelVo.setIsActive(list.get(0).getIsActive());
				volist.add(userLevelVo); 
			}
		}
		return volist;
	}
	
	/**
	 * 获取用户下级
	 * @param userId
	 * @return
	 */
	public List<UserLevelVo> getUperUsersMallList(String parentId,String level,String mineId,UsersMall users) {
		List<UserLevelVo> resultList= new ArrayList<UserLevelVo>();
		if (StringHelper.isNotBlank(parentId)) {
			UsersMall inviteUser = this.usersMallDao.selectByPrimaryKey(parentId);
			String inviteUserName = inviteUser.getUserNickName();
			String inviteCode = inviteUser.getInvitingCode();
			UsersMallExample example = new UsersMallExample();
			Criteria criteria = example.createCriteria();
			criteria.andParentIdEqualTo(parentId);
			criteria.andIdNotEqualTo(mineId);
			criteria.andIsEffectiveEqualTo(DBConst.TRUE);
			if(users != null){
				Date startTime = users.getCreateTime();
				Date endTime = users.getUpdateTime();
				if(startTime != null && endTime != null){
					criteria.andCreateTimeBetween(startTime, endTime);
				}
			}
			List<UsersMall> list = this.usersMallDao.selectByExample(example);
			if(list.size()>0){
				for(UsersMall usersMall:list){
					UserLevelVo userLevelVo = new UserLevelVo();
					userLevelVo.setId(usersMall.getId());
					userLevelVo.setLevelDesc(level);
					userLevelVo.setUserNickName(usersMall.getUserNickName());
					userLevelVo.setLaiyuan(usersMall.getIsActive());
					userLevelVo.setTotalComsum(usersMall.getTotalComsum());
					userLevelVo.setUserPhone(usersMall.getUserPhone());
					userLevelVo.setIsActive(usersMall.getIsActive());
					userLevelVo.setInviteCode(inviteCode);
					userLevelVo.setInviteUserName(inviteUserName);
					userLevelVo.setCreateTime(usersMall.getCreateTime());
		   			Integer orderCount = getOrdersCount(usersMall.getId());
					userLevelVo.setOrderCount(orderCount);
					resultList.add(userLevelVo); 
				}
			}
		}
		return resultList;
	}
	public Integer getOrdersCount(String yunUserId){
   		Integer count = 0;
   		if(StringHelper.isNotBlank(yunUserId)){
   			OrdersDetailExample example = new OrdersDetailExample();
   	   		OrdersDetailExample.Criteria criteria = example.createCriteria();
   	   		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
   	   		criteria.andYunUserIdEqualTo(yunUserId);
   	   		List<OrdersDetail> list = this.ordersDetailDao.selectByExample(example);
   	   		count = list.size();
   		}
   		return count;
   	}
 	/**
 	 * 根据用户Id和相关条件查找相关用户数据
 	 * @param id 店主id
 	 * @param userNickName
 	 * @param userPhone
 	 * @param levelDesc 级别信息
 	 * @param user
 	 * @return
 	 */
   	public Map<String, Object> getUserInfo(String id,String userNickName,String userPhone,String levelDesc,UsersMall user){
   		Map<String, Object> resultMap = new HashMap<String, Object>();
   		List<Map<String, Object>> resultList = new ArrayList<Map<String, Object>>();
   		List<Map<String, Object>> yunList = new ArrayList<Map<String, Object>>();
   		List<Map<String, Object>> oneList = new ArrayList<Map<String, Object>>();
   		List<Map<String, Object>> twoList = new ArrayList<Map<String, Object>>();
   		List<Map<String, Object>> upperList = new ArrayList<Map<String, Object>>();
   		int total = 0;
  	   		if (StringHelper.isNotBlank(id)) {
  	   			UsersMall usersMall = this.usersMallDao.selectByPrimaryKey(id);
  	   			if(usersMall != null){
  	   				String type= usersMall.getType();
  	   				//用户关系类型(001:店主，002：上级，003：一级下级：004：二级下级)
  	   				if(StringHelper.isNotBlank(levelDesc)){
  	   					//取店主信息
  	   					if(levelDesc.equals(TeamLevel.My.getLevel())){
  	   						//普通用户，有云店主
  	    	   				if(type.equals(UserType.user.getType())){
  	    	   					String yunId = usersMall.getYunId();
  	    	   					if(StringHelper.isNotBlank(yunId)){
  	    	   						List<UserLevelVo> list = getUsersMallList(yunId,TeamLevel.My.getName());
  	    	   	   					if(list.size()>0){
  	    	   	   						yunList = ValueHelper.tranList2MapList(list, ignoreProperties);
  	    	   	   	   					total = 1;
  	    	   	   					}
  	    	   					} 					
  	    	   				}
  	   					}
  	   					//取上级信息
  	   					if(levelDesc.equals(TeamLevel.Uper.getLevel())){
  	  	   		   			//获取用户上级信息
  	  	   					String parentId = usersMall.getParentId();
  	  	   					if(StringHelper.isNotBlank(parentId)){
  	  	   						List<UserLevelVo> list = getUsersMallList(parentId,"上级");
  	  	   	   					if(list.size()>0){	
  	  	   	   			   		total = list.size();
  	  	   	   			        upperList = ValueHelper.tranList2MapList(list, ignoreProperties);
  	  	   	   					} 	  	   	   					
  	  	   					}  	  	   				
  	   					}
  	   					//取用户一级下级
  	   					if(levelDesc.equals(TeamLevel.One.getLevel())){
  	  	   					String parentId = usersMall.getParentId();
  	  	   					if(StringHelper.isNotBlank(parentId)){ 	  	   						
  	  	   	   					//获取用户下级信息
  	  	   	   				    List<UserLevelVo> downList = getUperUsersMallList(parentId,"一级下级",id,null);
  	  	   	   				    if(downList.size()>0){
  	  	   	   				    	total = total + downList.size();
  	  	   	   	   				    oneList = ValueHelper.tranList2MapList(downList, ignoreProperties);
  	  	   	   				    }	
  	  	   					} 	  	   				
  	   					}
  	   					//二级下级
  	   					if(levelDesc.equals(TeamLevel.Two.getLevel())){
  	  	   		   			//获取用户上级信息
  	  	   					String parentId = usersMall.getParentId();
  	  	   					if(StringHelper.isNotBlank(parentId)){ 	  	   						
  	  	   	   					//获取用户下级信息
  	  	   	   				    List<UserLevelVo> downList = getUperUsersMallList(parentId,"一级下级",id,null);
  	  	   	   				    if(downList.size()>0){
  	  	   	   				    	total = total + downList.size();
  	  	   	   	   				    //获取用户下下级
  	  	  							for (UserLevelVo users : downList) {
  	  	  								//每个用户作为上级找他的一级下级
  	  	  								String userId = users.getId();
  	  	  								List<UserLevelVo> secdownList = getUperUsersMallList(userId,"二级下级",id,null);
  	  	  								if(secdownList.size()>0){
  	  	  									total = total + secdownList.size();
  	  	  									List<Map<String, Object>> beforetwoList = new ArrayList<Map<String, Object>>();
  	  	  	  						   		beforetwoList = ValueHelper.tranList2MapList(secdownList, ignoreProperties);
  	  	  	  						   		twoList.addAll(beforetwoList);
  	  	  								}							
  	  	  							}
  	  	   	   				    }	
  	  	   					}  	  	   				
  	   					}
  	   				}else{
  	   				//普通用户，有云店主
  	  	   				if(type.equals(UserType.user.getType())){
  	  	   					String yunId = usersMall.getYunId();
  	  	   					if(StringHelper.isNotBlank(yunId)){
  	  	   						List<UserLevelVo> list = getUsersMallList(yunId,"云店主",userNickName,userPhone);
  	  	   	   					if(list.size()>0){
  	  	   	   						yunList = ValueHelper.tranList2MapList(list, ignoreProperties);
  	  	   	   	   					total = 1;
  	  	   	   					}
  	  	   					} 					
  	  	   				}
  	  	   				//云用户，有邀请人和两个下级
  	  	   				if(type.equals(UserType.ydz.getType())){
  	  	   		   			//获取用户上级信息
  	  	   					String parentId = usersMall.getParentId();
  	  	   					if(StringHelper.isNotBlank(parentId)){
  	  	   						List<UserLevelVo> list = getUsersMallList(parentId,"上级",userNickName,userPhone);
  	  	   	   					if(list.size()>0){	
  	  	   	   			   		total = list.size();
  	  	   	   			        upperList = ValueHelper.tranList2MapList(list, ignoreProperties);
  	  	   	   					}
  	  	   	   					//获取用户下级信息
  	  	   	   				    List<UserLevelVo> downList = getUperUsersMallList(parentId,"一级下级",id,userNickName,userPhone);
  	  	   	   				    if(downList.size()>0){
  	  	   	   	   				    oneList = ValueHelper.tranList2MapList(downList, ignoreProperties);
  	  	   	   				    }else{
  	  	   	   				    	total = total + downList.size();
  	  	   	   	   				    downList = getUperUsersMallList(parentId,"一级下级",id,null);
  	  	   	   	   				    if(downList.size()>0){
  	  	   	   	   				    	//获取用户下下级
  	  	  	  							for (UserLevelVo users : downList) {
  	  	  	  								//每个用户作为上级找他的一级下级
  	  	  	  								String userId = users.getId();
  	  	  	  								List<UserLevelVo> secdownList = getUperUsersMallList(userId,"二级下级",parentId,userNickName,userPhone);
  	  	  	  								if(secdownList.size()>0){
  	  	  	  									total = total + secdownList.size();
  	  	  	  									List<Map<String, Object>> beforetwoList = new ArrayList<Map<String, Object>>();
  	  	  	  	  						   		beforetwoList = ValueHelper.tranList2MapList(secdownList, ignoreProperties);
  	  	  	  	  						   		twoList.addAll(beforetwoList);
  	  	  	  								}							
  	  	  	  							}
  	  	   	   	   				    }  
  	  	   	   				    }
  	  	   	   					
  	  	   					}
  	  	   				} 	  	   				
  	   				}
  	   				if(yunList.size()>0){
  		   	   		   	resultList.addAll(yunList);
  	   				}
  	   				if(oneList.size()>0){
  		   	   		   	resultList.addAll(oneList);

  	   				}
  	   				if (twoList.size() > 0) {
  						resultList.addAll(twoList);
  					}
  	   				if(upperList.size()>0){
  		   	   		   	resultList.addAll(upperList);
  	   				}
  	   			} 	   			
  	   		} else {
  	   			throw new ParameterErrorException();
  	   		}
  	   	    // 数据返回处理
  	   		resultMap.put(IticConst.TOTAL_RECORDS, total);
  	   		resultMap.put(IticConst.DISPLAY_RECORDS, total);
  	   		resultMap.put(IticConst.RESULT, ResponseCode.SUCCESS.getCode());
  	   		resultMap.put(IticConst.DATA, resultList);
   		return resultMap;
   	}
   	
   	/**
	 * 根据用户ID和某一用户名称查找该用户ID下的关系用户
	 * @param parentId
	 * @param level
	 * @param mineId
	 * @param userNickName
	 * @return
	 */
	public List<UserLevelVo> getUperUsersMallList(String parentId,String level,String mineId,String userNickName,String userPhone) {
		List<UserLevelVo> resultList= new ArrayList<UserLevelVo>();
		if (StringHelper.isNotBlank(parentId)) {
			UsersMallExample example = new UsersMallExample();
			Criteria criteria = example.createCriteria();
			criteria.andParentIdEqualTo(parentId);
			criteria.andIdNotEqualTo(mineId);
			criteria.andIsEffectiveEqualTo(DBConst.TRUE);
			List<UsersMall> list = this.usersMallDao.selectByExample(example);
			if(list.size()>0){
				for(UsersMall usersMall:list){
					if(StringHelper.isNotBlank(userNickName)){
						if(usersMall.getUserNickName().equals(userNickName)){
							UserLevelVo userLevelVo = new UserLevelVo();
							userLevelVo.setId(usersMall.getId());
							userLevelVo.setLevelDesc(level);
							userLevelVo.setUserNickName(usersMall.getUserNickName());
							userLevelVo.setLaiyuan(usersMall.getIsActive());
							userLevelVo.setTotalComsum(usersMall.getTotalComsum());
							userLevelVo.setUserPhone(usersMall.getUserPhone());
							userLevelVo.setIsActive(usersMall.getIsActive());
							resultList.add(userLevelVo); 
						}
					}
					if(StringHelper.isNotBlank(userPhone)){
						if(usersMall.getUserPhone().equals(userPhone)){
							UserLevelVo userLevelVo = new UserLevelVo();
							userLevelVo.setId(usersMall.getId());
							userLevelVo.setLevelDesc(level);
							userLevelVo.setUserNickName(usersMall.getUserNickName());
							userLevelVo.setLaiyuan(usersMall.getIsActive());
							userLevelVo.setTotalComsum(usersMall.getTotalComsum());
							userLevelVo.setUserPhone(usersMall.getUserPhone());
							userLevelVo.setIsActive(usersMall.getIsActive());
							resultList.add(userLevelVo); 
						}
					}
				}
			}
		}
		return resultList;
	}
   	
   	/**
	 * 根据局用户名称查找店主信息或者是上级信息
	 * @param userId
	 * @param levelDesc
	 * @param userNickName
	 * @return
	 */
	public List<UserLevelVo> getUsersMallList(String userId,String levelDesc,String userNickName,String userPhone) {
		List<UserLevelVo> volist = new ArrayList<UserLevelVo>();
		if (StringHelper.isNotBlank(userId)) {
			UsersMallExample example = new UsersMallExample();
			Criteria criteria = example.createCriteria();
			criteria.andIdEqualTo(userId);
			criteria.andIsEffectiveEqualTo(DBConst.TRUE);
			if(StringHelper.isNotBlank(userNickName)){
				criteria.andUserNickNameEqualTo(userNickName);
			}
			if(StringHelper.isNotBlank(userPhone)){
				criteria.andUserPhoneEqualTo(userPhone);
			}
			List<UsersMall> list = this.usersMallDao.selectByExample(example);
			if(list.size()>0){
				UserLevelVo userLevelVo = new UserLevelVo();
				userLevelVo.setId(list.get(0).getId());
				userLevelVo.setLevelDesc(levelDesc);
				userLevelVo.setUserNickName(list.get(0).getUserNickName());
				userLevelVo.setLaiyuan(list.get(0).getIsActive());
				userLevelVo.setTotalComsum(list.get(0).getTotalComsum());
				userLevelVo.setUserPhone(list.get(0).getUserPhone());
				userLevelVo.setIsActive(list.get(0).getIsActive());
				volist.add(userLevelVo); 
			}
		}
		return volist;
	}
	/**
	 * 用户注册
	 * @param phone
	 * @return
	 */
	public UsersMall reg( UsersMall usersMall ) {
		
		UsersMall unionUsers = null;
		if( StringHelper.isNotBlank(usersMall.getUnionid()) ){
			unionUsers = usersMallDao.getByUnionid(usersMall.getUnionid());
		}
		/*if( StringHelper.isNotBlank(usersMall.getOpenid()) ){
			unionUsers = usersMallDao.getByOpenid(usersMall.getOpenid());
		}*/
		if(  null == unionUsers ){
			this.initDefalutFields(usersMall);
			usersMall.setIsBlack(DBConst.FALSE);
			
			if( StringHelper.isBlank(usersMall.getUserPwd()) ){
				String randomString = RandomStringHelper.randomNumStr(6);
				usersMall.setUserPwd(randomString);
				//发送短信提醒
				phoneSendService.sendPwd(usersMall, randomString);
			}
			
			if( StringHelper.isBlank(usersMall.getType()) ){
				usersMall.setType(UserType.user.getType());
			}
			
			if( StringHelper.isBlank(usersMall.getUserNickName()) ){
				usersMall.setUserNickName(usersMall.getUserPhone());
			}
			
			if( StringHelper.isBlank(usersMall.getUserHeadImg()) ){
				String defaultValue = DefaultSysSettingKeyValue.defaultHeadImg.getValue();
				String sysValue = sysSettingDao.getByKey(DefaultSysSettingKeyValue.defaultHeadImg.getKey());
				if( StringHelper.isNotBlank(sysValue) ){
					defaultValue = sysValue;
				}
				usersMall.setUserHeadImg(defaultValue);
			}
			
			usersMallDao.insert(usersMall);
			//添加UB
			addUbi(usersMall);
			//添加优惠券
			this.usersCouponService.addUserRegistCoupon(usersMall);
			if(UserType.isYDZ(usersMall.getType()))
				this.addTeamCountByUsersMall(usersMall);
			return usersMall;
		}else{
			//update
			String userPhone = usersMall.getUserPhone();
			unionUsers.setUserPhone(userPhone);
			
			if( StringHelper.isBlank(unionUsers.getOpenid()) ){
				unionUsers.setOpenid(usersMall.getOpenid());
			}
			
			if( StringHelper.isBlank(unionUsers.getUserPwd()) ){
				if( StringHelper.isNotBlank(usersMall.getUserPwd())){
					unionUsers.setUserPwd(usersMall.getUserPwd());
				}else{
					String randomString = RandomStringHelper.randomString(6);
					unionUsers.setUserPwd(randomString);
					//发送短信提醒
					phoneSendService.sendPwd(usersMall, randomString);
				}
			}
			
			if( StringHelper.isBlank(unionUsers.getUserNickName()) ){
				if( StringHelper.isNotBlank(usersMall.getUserNickName()) ){
					unionUsers.setUserNickName(usersMall.getUserNickName());
				}else{
					unionUsers.setUserNickName(usersMall.getUserPhone());
				}
			}
			
			if( StringHelper.isBlank(unionUsers.getUserHeadImg()) ){
				if( StringHelper.isNotBlank(usersMall.getUserHeadImg())){
					unionUsers.setUserHeadImg(usersMall.getUserHeadImg());
				}else{
					String defaultValue = DefaultSysSettingKeyValue.defaultHeadImg.getValue();
					String sysValue = sysSettingDao.getByKey(DefaultSysSettingKeyValue.defaultHeadImg.getKey());
					if( StringHelper.isNotBlank(sysValue) ){
						defaultValue = sysValue;
					}
					unionUsers.setUserHeadImg(defaultValue);
				}
			}
			//update
			usersMallDao.updateByPrimaryKeySelective(unionUsers);
			return unionUsers;
		}
		
	}
	
	public List<UsersMall> getTeamByLevel(Condition condition){
		if(StringUtils.isNotEmpty(condition.getField())) {
			SortField file = SortField.getSortFile(condition.getField());
			if(file ==null)
				condition.setField(null);
			else
				condition.setField(file.getField());
		}
		List<UsersMall> list  = this.usersMallDao.getByCondition(condition);
		return list;
	}
	
	public int getCountByLevel(Condition condition){
		int count = this.usersMallDao.getCountByCondition(condition);
		return count;
	}
	
	public double getMySalesAmount(String userId,String yunId) {
		
		return 0.0;
	}
	
	public List<UsersMall> getInviteRecordByUserID(String userId,int start,int length){
		Map<String, Object> params = new HashMap<>();
		params.put("userId", userId);
		params.put("start", start);
		params.put("length", length);
		List<UsersMall> usersMalls = this.usersMallDao.getInviteRecordByUserID(params);
		return usersMalls;
	}
	
	public int getInviteRecordCount(String userId) {
		int count = this.usersMallDao.getInviteRecordCount(userId);
		return count;
	}

	public String ruzhuByCode(UsersMall user, OpenStore openStore) {
		usersMallDao.updateByPrimaryKeySelective(user);
		this.initDefalutFields(openStore);
		openStoreDao.insert(openStore);
		this.addTeamCountByUsersMall(user);
		return SUCCESS;
	}
	
	/**
	 * 获得VIP海报
	 * @param user
	 * @param money
	 * @return
	 */
	public String getInviteVipPoster( UsersMall user, String money ){
		String result = null;
		
		StringBuffer sb = new StringBuffer();
				
		String url = "http://file.jhjvip.cn:8888/image-server/uploadImage/oss/vip";
		
		sb.append("nickName=");
		sb.append(user.getUserNickName());
		sb.append("&money=");
		sb.append(money);
		
		String initUrl = DefaultSysSettingKeyValue.inviteVipLink.getValue()+user.getId();
		String sysWord = sysSettingDao.getByKey(DefaultSysSettingKeyValue.inviteVipLink.getKey());
		if( StringHelper.isNotBlank(sysWord) ){
			initUrl = sysWord+user.getId();
		}
		sb.append("&url="+initUrl);
		
		String sendPost = HttpRequestUtils.sendPost(url, sb.toString());
		JSONObject fromObject = JSONObject.fromObject(sendPost);
		String resultRemote = fromObject.getString("errorCode");
		if( "10000".equals(resultRemote)){
			result = fromObject.getString("data");
		}
		return result;
		
	}

	/**
	 * 邀请云店主合成图片
	 * @param user
	 * @return
	 */
	public String getInviteYunPoster(UsersMall user) {
		String result = null;
		
		StringBuffer sb = new StringBuffer();
		//String url = "http://localhost:8090/image-server/uploadImage/oss/good";
		String url = "http://file.jhjvip.cn:8888/image-server/uploadImage/oss/yun";
		
		sb.append("userHeadImage=");
		sb.append(user.getUserHeadImg());
		sb.append("&nickName=");
		sb.append(user.getUserNickName());
		
		String initUrl = DefaultSysSettingKeyValue.inviteYunLink.getValue()+user.getId();
		String sysWord = sysSettingDao.getByKey(DefaultSysSettingKeyValue.inviteYunLink.getKey());
		if( StringHelper.isNotBlank(sysWord) ){
			initUrl = sysWord+user.getId();
		}
		sb.append("&url="+initUrl);
		String sendPost = HttpRequestUtils.sendPost(url, sb.toString());
		JSONObject fromObject = JSONObject.fromObject(sendPost);
		String resultRemote = fromObject.getString("errorCode");
		if( "10000".equals(resultRemote)){
			result = fromObject.getString("data");
		}
		return result;
	}


	/**
	 * 猎取二维码
	 * @param user
	 * @return
	 */
	public String getInvitingQcode(UsersMall user) {
		String result = null;
		
		StringBuffer sb = new StringBuffer();
		//String url = "http://localhost:8090/image-server/uploadImage/oss/good";
		String url = "http://file.jhjvip.cn:8888/image-server/uploadImage/oss/qcode";
		
		/*String initUrl = "http://down.huifakeji.com/dist/index.html#/Vipinvitenter?id="+user.getId();
		String temp = sysSettingDao.getByKey("SHARE_VIP_QCODE_URL");
		if( StringHelper.isNotBlank(temp) ){
			initUrl = temp;
		}*/
		
		String initUrl = DefaultSysSettingKeyValue.inviteYunLink.getValue()+user.getId();
		String sysWord = sysSettingDao.getByKey(DefaultSysSettingKeyValue.inviteYunLink.getKey());
		if( StringHelper.isNotBlank(sysWord) ){
			initUrl = sysWord+user.getId();
		}
		sb.append("url="+initUrl);
		sb.append(initUrl);
		String sendPost = HttpRequestUtils.sendPost(url, sb.toString());
		JSONObject fromObject = JSONObject.fromObject(sendPost);
		String resultRemote = fromObject.getString("errorCode");
		if( "10000".equals(resultRemote)){
			result = fromObject.getString("data");
		}
		return result;
	}
	
	/**
	 * 猎取二维码
	 * @param user
	 * @return
	 */
	public String getInvitingYunQcode(UsersMall user) {
		String result = null;
		
		StringBuffer sb = new StringBuffer();
		//String url = "http://localhost:8090/image-server/uploadImage/oss/good";
		String url = "http://file.jhjvip.cn:8888/image-server/uploadImage/oss/qcode";
		
		/*String initUrl = "http://down.huifakeji.com/dist/index.html#/Yuninvitenter?id="+user.getId();
		String temp = sysSettingDao.getByKey("SHARE_YUN_QCODE_URL");
		if( StringHelper.isNotBlank(temp) ){
			initUrl = temp;
		}*/
		
		String initUrl = DefaultSysSettingKeyValue.inviteYunLink.getValue()+user.getId();
		String sysWord = sysSettingDao.getByKey(DefaultSysSettingKeyValue.inviteYunLink.getKey());
		if( StringHelper.isNotBlank(sysWord) ){
			initUrl = sysWord+user.getId();
		}
		
		sb.append("url="+initUrl);
		String sendPost = HttpRequestUtils.sendPost(url, sb.toString());
		JSONObject fromObject = JSONObject.fromObject(sendPost);
		String resultRemote = fromObject.getString("errorCode");
		if( "10000".equals(resultRemote)){
			result = fromObject.getString("data");
		}
		return result;
	}
	
	/**
	 * 添加用户统计云店主和下级
	 * @param usersMall
	 */
	public void addTeamCountByUsersMall(UsersMall usersMall) {
		if(usersMall.getParentId()!=null && StringUtils.isNotEmpty(usersMall.getParentId())) {
			UsersMall parentOneUsersMall = this.get(usersMall.getParentId());
			if(parentOneUsersMall!=null) {
				int peopleOne = parentOneUsersMall.getSuccessPeopleOne()==null?0:parentOneUsersMall.getSuccessPeopleOne();
				peopleOne++;
				parentOneUsersMall.setSuccessPeopleOne(peopleOne);
				this.edit(parentOneUsersMall);
				
				StoreInfo  parentOneStore = this.storeInfoService.getByUserIdAndYunId(usersMall.getId());
				if(parentOneStore!=null){
					parentOneStore.setOneLevelCount(peopleOne);
					int teamCount = parentOneStore.getTeamCount()==null?0:parentOneStore.getTeamCount();
					teamCount++;
					parentOneStore.setTeamCount(teamCount);
					this.storeInfoService.edit(parentOneStore);
				}
				
				if(parentOneUsersMall.getParentId()!=null && parentOneUsersMall.getParentId().length()>0) {
					UsersMall parentTwoUsersMall = this.get(parentOneUsersMall.getParentId());
					if(parentTwoUsersMall!=null) {
						int peopleTwo = parentTwoUsersMall.getSuccessPeopleTwo()==null?0:parentTwoUsersMall.getSuccessPeopleTwo();
						peopleTwo++;
						parentOneUsersMall.setSuccessPeopleTwo(peopleTwo);;
						this.edit(parentTwoUsersMall);
						
						StoreInfo  parentTwoStore = this.storeInfoService.getByUserIdAndYunId(parentOneUsersMall.getParentId());
						if(parentTwoStore!=null){
							parentTwoStore.setTwoLevelCount(peopleTwo);
							int teamCount = parentTwoStore.getTeamCount()==null?0:parentTwoStore.getTeamCount();
							teamCount++;
							parentTwoStore.setTeamCount(teamCount);
							this.storeInfoService.edit(parentTwoStore);
						}
					}
				}
			}
		}
		this.storeInfoService.addStoreInfo(usersMall);
	}
	
	/**
	 * 根据用户邀请码得到用户信息
	 */
	public UsersMall getUserByInviteCode( String code ){
		UsersMall users = null;
		UsersMallExample example = new UsersMallExample();
		Criteria criteria = example.createCriteria();
		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
		criteria.andInvitingCodeEqualTo(code);
		List<UsersMall> tempList = usersMallDao.selectByExample(example);
		if( tempList.size()==1 ){
			users = tempList.get(0);
		}
		return users;
	}
	/**
	 * 获取用户最近邀请的人数
	 * @param userId
	 * @param days
	 * @return
	 */
	public int  getUserInviteCountLatelyDays(String userId,Date days) {
		Map<String, Object> params = new HashMap<>();
		params.put("userId", userId);
		params.put("date", days);
		int count = this.usersMallDao.getInviteCountByUserAndDays(params);
		return count;
	}
	/**
	 * 查看用户的花钱记录
	 * @param userId
	 */
	public List<Map<String,Object>> findConsumeLog(String userId,int start,int length) {
		Map<String, Object> params = new HashMap<>();
		params.put("userId", userId);
		params.put("start", start);
		params.put("length", length);
		List<Map<String,Object>> data = new ArrayList<>();
		data = this.usersMallDao.findUserConsumeLog(params);
		return data;
	}
	/**
	 * 获取云店主邀请关系列表
	 * @return
	 */
	/*public List<UserInviteRelateVo> getInviteRelate(){
		List<UserInviteRelateVo> returnList = new ArrayList<UserInviteRelateVo>();
		List<Map<String,Object>> map = this.usersMallDao.getInviteRelate();
		for(Map<String,Object> maps:map){
			UserInviteRelateVo Vo = new UserInviteRelateVo();
			Vo.setMycode(maps.get("mycode").toString());
			Vo.setMycreateTime(maps.get("mycreateTime").toString());
			Vo.setMyid(maps.get("myid").toString());
			Vo.setMyname(maps.get("myname").toString());
			Vo.setMyphone(maps.get("myphone").toString());
			Vo.setUperCode(maps.get("uperCode").toString());
			Vo.setUperid(maps.get("uperid").toString());
			Vo.setUperName(maps.get("uperName").toString());
			returnList.add(Vo);
		}
		return returnList;
	}*/
	public List<UsersMall> findUsersMallByType(UserType userType){
		
		UsersMallExample example = new UsersMallExample();
		Criteria criteria = example.createCriteria();
		criteria.andIsEffectiveEqualTo(DBConst.TRUE);
		criteria.andTypeEqualTo(userType.getType());
		List<UsersMall> usersMalls= usersMallDao.selectByExample(example);
		return usersMalls;
		
	}
	
	public String addUserLivingMOney(OrdersDetail ordersDetail,TaxCompany taxCompany) {
		UsersMall usersMall = this.get(ordersDetail.getUserId());
		String yunId=null;
		if(ordersDetail.getYunUserId()!=null)
			yunId = ordersDetail.getYunUserId();
		else {
			if(usersMall.getParentId()!=null)
				yunId = usersMall.getParentId();
		}
		UsersMall yunUser = this.get(yunId);
		List<OrdersItem> ordersItems = this.ordersItemService.getOrderItemsByOrderNo(ordersDetail.getOrderNo());
		double totalRemainMoney = 0;
		for(OrdersItem ordersItem: ordersItems) {
			GoodsSku goodsSku = this.goodsSkuService.get(ordersItem.getSkuId());
			double remainMoney = this.payUserlogService.calRemainCommission(yunUser, Double.toString(goodsSku.getSkuProfit()), taxCompany, ordersItem.getCount());
			totalRemainMoney+=remainMoney;
		}
		double livingMoney = usersMall.getLivingMoney()==null?0:usersMall.getLivingMoney();
		livingMoney +=totalRemainMoney;
		usersMall.setLivingMoney(livingMoney);
		String result = this.edit(usersMall);
		if(result.equals(SUCCESS))
			result = this.financeUserMakeMoneyLogService.addMakeMoneyLog(usersMall.getId(), totalRemainMoney, ordersDetail.getOrderNo());
		return result;
	}
	public void livingMoney(UsersMall usersMall,UsersMall yunUser,String commission,TaxCompany taxCompany,int count,double consume) {
		//查询用户之前的生钱佣金
		double livingMoney = usersMall.getLivingMoney()==null?0:usersMall.getLivingMoney();
		//计算普通用户的年利率
		LivingRateResultVo livingRateResultVo = this.livingRateService.calUserLivingRate(usersMall);
		if(livingRateResultVo!=null && livingRateResultVo.getYearRate()>=0) {
			//计算用户的生钱
			String yearRate = Double.toString(livingRateResultVo.getYearRate());
			String money = this.livingRateService.calLivingMoney(yearRate, commission);
			//修改用户余额
			double banlance = usersMall.getMoney()==null?0:usersMall.getMoney();
			banlance+=Double.parseDouble(money)<=0?0:Double.parseDouble(money);
			usersMall.setMoney(banlance);
			//修改用户生钱的钱数
			usersMall.setLivingMoney(livingMoney);
			this.edit(usersMall);
			//添加生钱记录
			this.financeUserMakeMoneyService.addFinanceUserMakeMoney(usersMall.getId(), livingRateResultVo, Double.parseDouble(money), consume);
		}
	}
	
	public void livingMoney(UsersMall usersMall) {
		//查询用户之前的生钱佣金
		double livingMoney = usersMall.getLivingMoney()==null?0:usersMall.getLivingMoney();
		if(livingMoney>0){
			//计算普通用户的年利率
			LivingRateResultVo livingRateResultVo = this.livingRateService.calUserLivingRate(usersMall);
			if(livingRateResultVo!=null && livingRateResultVo.getYearRate()>=0) {
				String yearRate = Double.toString(livingRateResultVo.getYearRate());
				//计算用户的生钱
				String money = this.livingRateService.calLivingMoney(yearRate, Double.toString(livingMoney));
				//修改用户余额
				double banlance = usersMall.getMoney()==null?0:usersMall.getMoney();
				banlance+=Double.parseDouble(money)<=0?0:Double.parseDouble(money);
				usersMall.setMoney(banlance);
				//修改用户生钱的钱数
				usersMall.setLivingMoney(livingMoney);
				this.edit(usersMall);
				//添加生钱记录
				Date date = DateHelper.addDays(DateHelper.parseDate(DateHelper.getDate()), -1);
				double conusme = this.ordersItemService.getUserConsumeByDays(usersMall.getId(), date);
				this.financeUserMakeMoneyService.addFinanceUserMakeMoney(usersMall.getId(), livingRateResultVo, Double.parseDouble(money),conusme );
				List<UsersHelp> usersHelps = this.usersHelpService.findNotCalUsersHelp(usersMall.getId());
				for(UsersHelp usersHelp:usersHelps) {
					usersHelp.setIsCal("1");
					this.usersHelpService.edit(usersHelp);
				}
			
			}
		}
	}
	
}